//
//  XDAttachManagerViewController.m
//  iphone.mobileoa
//
//  Created by 李亚春 on 13-5-31.
//  Copyright (c) 2013年 Epoint. All rights reserved.
//

#import "XDAttachManagerViewController.h"
#import "XDAttachManagerListCell.h"
#import "RIButtonItem.h"
#import "UIAlertView+Blocks.h"
#import "AttachManagerService.h"

@interface XDAttachManagerViewController ()
{
    NSMutableArray *filesArray;
}
@end

@implementation XDAttachManagerViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIButton* rightButton= [[UIButton alloc] initWithFrame:CGRectMake(0,0,40,20)];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"img_top_trash"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(deleteAllFile) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = leftBarButtonItem;
    [leftBarButtonItem release];
    [rightButton release];
    
    filesArray = [[NSMutableArray alloc]init];
    [self refreshFile];
}

-(void)refreshFile
{
    filesArray = [[AttachManagerService getAllAttachFile]retain];
    [self.tv reloadData];
}

-(void)deleteAllFile
{
    RIButtonItem *okItem = [RIButtonItem item];
    okItem.label = @"确定";
    okItem.action = ^
    {
        for (int i=0; i<filesArray.count; i++) {
            NSDictionary *dic = [filesArray objectAtIndex:i];
            NSError *error = nil;
            [[NSFileManager defaultManager] removeItemAtPath:[dic objectForKey:@"filepath"] error:&error];
            if (error!=nil) {
                [UITool toast:[NSString stringWithFormat:@"%@",error]];
            }
        }
        [self refreshFile];
    };
    
    RIButtonItem *cancelItem = [RIButtonItem item];
    cancelItem.label = @"取消";
    
    UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确定清空所有附件吗？" cancelButtonItem:cancelItem otherButtonItems:okItem,nil];
    [alter show];
    [alter release];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma tableview

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellItem = @"CellItem";
    XDAttachManagerListCell *cell = (XDAttachManagerListCell *)[tableView dequeueReusableCellWithIdentifier:CellItem];
    if (cell==nil) {
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"XDAttachManagerListCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    NSMutableDictionary *m = [filesArray objectAtIndex:indexPath.row];
    NSString *filename = [m objectForKey:@"filename"];
    if ([filename hasSuffix:@".doc"]||[filename hasSuffix:@".docx"]) {
        cell.ivIcon.image = [UIImage imageNamed:@"img_attach_doc"];
    }
    else if([filename hasSuffix:@"xls"]||[filename hasSuffix:@".xlsx"])
    {
        cell.ivIcon.image = [UIImage imageNamed:@"img_attach_excel"];
    }
    else if([filename hasSuffix:@"pdf"])
    {
        cell.ivIcon.image = [UIImage imageNamed:@"img_pdf_48"];
    }
    else if([filename hasSuffix:@"txt"])
    {
        cell.ivIcon.image = [UIImage imageNamed:@"img_txt_48"];
    }
    else if([filename hasSuffix:@"jpg"])
    {
        cell.ivIcon.image = [UIImage imageNamed:@"img_jpg_48"];
    }
    cell.lbFilename.text = [m objectForKey:@"filename"];
    cell.accessoryType = UITableViewCellSelectionStyleBlue;
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return filesArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *m = [filesArray objectAtIndex:indexPath.row];
    NSString *filepath = [m objectForKey:@"filepath"];
    [self openFileFromSecondApp:filepath];
}

- (void)dealloc {
    [_tv release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setTv:nil];
    [super viewDidUnload];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tv editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	return UITableViewCellEditingStyleDelete;

}


//点击删除按钮后, 会触发如下事件. 在该事件中做响应动作就可以了
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle  forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableDictionary *m = [filesArray objectAtIndex:indexPath.row];
    NSString *filepath = [m objectForKey:@"filepath"];
    NSError *error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:filepath error:&error];
    [self refreshFile];
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    [self doSearch:searchBar];
    
}

- (void)doSearch:(UISearchBar *)searchBar{
    
    NSMutableArray *ftemp = [[NSMutableArray alloc]init];
    
    for (int i=0; i<filesArray.count; i++) {
        NSMutableDictionary *m = [filesArray objectAtIndex:i];
        NSString *filename = [m objectForKey:@"filename"];
        NSLog(@"%i",[StringUtil contains:[filename lowercaseString] :[searchBar.text lowercaseString]]);
        if ([StringUtil contains:[filename lowercaseString] :[searchBar.text lowercaseString]]) {
            [ftemp addObject:m];
        }
    }
    [filesArray release];
    filesArray = [ftemp retain];
    [ftemp release];
    
    [self.tv reloadData];
    [filesArray release];
    filesArray = [[AttachManagerService getAllAttachFile]retain];
}

@end
